package com.ff.miaosha.access;

import com.alibaba.fastjson.JSON;
import com.ff.miaosha.domain.MiaoshaUser;
import com.ff.miaosha.redis.AccessKey;
import com.ff.miaosha.redis.RedisService;
import com.ff.miaosha.result.CodeMsg;
import com.ff.miaosha.result.Result;
import com.ff.miaosha.service.MiaoshaUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Service
public class AccessInterceptor implements HandlerInterceptor {

    @Autowired
    MiaoshaUserService userService;

    @Autowired
    RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            MiaoshaUser user=getUser(request,response);
            UserContext.setUser(user);
            HandlerMethod hm= (HandlerMethod) handler;
            AccessLimit accessLimit=hm.getMethodAnnotation(AccessLimit.class);
            if (accessLimit==null){
                return true;
            }
            int seconds=accessLimit.seconds();
            int maxCount=accessLimit.maxCount();
            boolean needLogin=accessLimit.needLogin();
            String key=request.getRequestURI();
            if (needLogin){
                if (user==null){
                    render(response, CodeMsg.SERVER_ERROR);
                    return false;
                }
                key+="_"+user.getId();
            }else{
                // do nothing
            }
            AccessKey ak=AccessKey.withExpire(seconds);
            Integer count=redisService.get(ak,key,Integer.class);
            if (count==null){
                redisService.set(ak,key,1);
            }else if (count<maxCount){
                redisService.incr(ak,key);
            }else{
                render(response,CodeMsg.ACCESS_LIMIT_REACHED);
                return false;
            }

        }
        return true;
    }

    private MiaoshaUser getUser(HttpServletRequest request, HttpServletResponse response) {
        String paramToken=request.getParameter(MiaoshaUserService.COOKIE_NAME_TOKEN);
        String cookieToken=getCookieValue(request,MiaoshaUserService.COOKIE_NAME_TOKEN);
        if (StringUtils.isEmpty(cookieToken)&&StringUtils.isEmpty(paramToken)){
            return null;
        }
        String token=StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
        return userService.getByToken(response,token);
    }

    private String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies=request.getCookies();
        if (cookies==null || cookies.length<0){
            return null;
        }
        for(Cookie cookie: cookies){
            if (cookie.getName().equals(cookieName)){
                return  cookie.getValue();
            }
        }
        return null;
    }

    private void render(HttpServletResponse response,CodeMsg cm) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out=response.getOutputStream();
        String str= JSON.toJSONString(Result.error(cm));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
